package com.yunc.common.web.aspect;

import com.yunc.common.core.constant.AuthConstants;
import com.yunc.common.web.exception.SecurityException;
import com.yunc.common.web.util.JwtTokenUtils;
import com.yunc.common.web.util.UserContext;
import com.yunc.common.web.util.WebUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class CheckLoginAspect {

    /**
     * 配置织入点
     */
    @Pointcut("@annotation(com.yunc.common.web.aspect.CheckLogin)")
    public void pointCut() {

    }

    @Before(value = "pointCut()")
    public void checkLogin(JoinPoint point) {
        String token = WebUtils.getRequestParameter(AuthConstants.TOKEN);
        // token不能为空
        if (StringUtils.isBlank(token)){
            throw new SecurityException("Token不能为空");
        }
        boolean flag;
        try {
            flag = JwtTokenUtils.isExpiration(token);
        } catch (Exception e) {
            throw new SecurityException("Token不合法");
        }
        if (flag) {
            throw new SecurityException("Token不合法");
        }
        Claims claims = JwtTokenUtils.getTokenBody(token);
        UserContext.setUserId((String) claims.get(UserContext.CONTEXT_KEY_USER_ID));
    }

    @After(value = "pointCut()")
    public void after() {
        UserContext.remove();
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private CheckLogin getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(CheckLogin.class);
        }
        return null;
    }

}
